<template>
  <a-drawer
    :visible="visible"
    :title="title"
    placement="right"
    :footer-style="{ textAlign: 'center' }"
    width="600"
    @close="cancelClick"
  >
    <template v-if="!loading">
      <a-form layout="vertical">
        <a-form-item label="角色名称" v-bind="validateInfos.name">
          <a-input
            v-model:value="modelRef.name"
            placeholder="请输入角色名称"
            allowClear
          />
        </a-form-item>
        <a-form-item label="状态" v-bind="validateInfos.status">
          <a-switch
            v-model:checked="modelRef.status"
            checked-children="启用"
            un-checked-children="禁用"
          />
        </a-form-item>
        <a-form-item label="选择权限" v-bind="validateInfos.checkedKeys">
          <a-tree
            defaultExpandAll
            v-model:selectedKeys="modelRef.selectedKeys"
            @select="onNodeClick"
            v-model:checkedKeys="modelRef.checkedKeys"
            checkable
            :tree-data="treeData"
          >
          </a-tree>
        </a-form-item>
      </a-form>
    </template>
    <template v-else>
      <a-spin :spinning="loading" class="loading-wrapper"></a-spin>
    </template>

    <template #footer>
      <a-button
        style="
          margin-right: 8px;
          width: 200px;
          border: 1px solid #d9d9d9;
          color: #000;
          border-radius: 5px;
        "
        @click="cancelClick"
        >取消</a-button
      >
      <a-button
        type="primary"
        style="width: 200px; border: none; border-radius: 5px"
        @click="confirmClick"
        >保存</a-button
      >
    </template>
  </a-drawer>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, watch } from "vue";
import { Form } from "ant-design-vue";
const useForm = Form.useForm;
import routes from "@/router/router.config.js";
import _ from "lodash";
import request from "@/common/utils/request";
import { useRoute, useRouter } from "vue-router";
import { Modal, message } from "ant-design-vue";
// 数字人定制路由
import {getOnly_digital_human} from '@/common/utils/atherUtils.js'
import {haveRouters} from '@/router/customizedRouters.js'
export default defineComponent({
  name: "StaffDrawer",
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: "",
    },
  },
  setup(props, { emit }) {
    const route = useRoute();
    const state = reactive({
      loading: false,
      count: 0,
      treeData: [],
      roleOptions: [
        {
          value: "1",
          label: "超级管理员",
        },
      ],
      clipRole: [],
    });

    const getTreeData = async() => {
      let currentRoutePath = route.path;
      // 不同路由返回对应路由配置文件中的路由配置数据
      let routeName = route.path.includes("workShotstack")
        ? "workShotstack"
        : "SocialMedia";
      // 获取路由列表
      let workShotstack = routes.find((item) => item.name == routeName);
      let workShotstackRoutes = _.cloneDeep(
        workShotstack ? workShotstack.children : []
      );

      const isGetOnly_digital_human = await getOnly_digital_human()
      // 如果是 数字人定制路由
      if (isGetOnly_digital_human) {
        // 可包含的路由配置项
        const routers = haveRouters()

        // 清空不包含的路由配置项
        const clearAtherRouter = (menuItems) => {
          if(menuItems?.children?.length) {
            menuItems.children.forEach((item, index) => {
              if(!routers.includes(item.name)) {
                menuItems.children.splice(index, 1);
                clearAtherRouter(item)
              }
            })
          }
        }
        workShotstackRoutes.forEach((item, index) => {
          if(!routers.includes(item.name)) {
            workShotstackRoutes.splice(index, 1);
            clearAtherRouter(item)
          }
        })
      }

      console.log(workShotstackRoutes,'workShotstackRoutes')

      let getFilterHideRoutes = (menuItems) => {
        return menuItems.filter((menu) => {
          // 如果当前菜单项被隐藏(账号中心除外)，则返回 false
          if (menu.meta.hidden && menu.meta.title != "账号中心") {
            return false;
          }

          // 如果有子菜单项，递归过滤子菜单项
          if (menu.children && menu.children.length > 0) {
            menu.children = getFilterHideRoutes(menu.children);
          }

          // 返回 true，表示当前菜单项是可见的
          return true;
        });
      };
      // 获取过滤hidden的路由列表    如果后台
      let filterHideRoutes = getFilterHideRoutes(workShotstackRoutes);
      filterHideRoutes.forEach((item) => {
        if (item.name === "CreationCenter") {
          item.children?.forEach((it) => {
            if (it.name === "MixedCutIntroduction") {
              it.disabled = !state.clipRole.includes("sphj");
            }
            if (it.name === "ScriptingTool") {
              it.disabled = !state.clipRole.includes("jbjj");
            }

            if (it.name === "GraphicEditing") {
              it.disabled = !state.clipRole.includes("twjj");
            }
            if (it.name === "AddVideoIntelligentSplit") {
              it.disabled = !state.clipRole.includes("spzncf");
            }
            if (it.name === "CreativityTools") {
              it.children = [
                {
                  name: "wzzyy",
                  disabled: !state.clipRole.includes("wzzyy"),
                  meta: {
                    title: "文字转语音",
                  },
                },
                {
                  name: "aicz",
                  disabled: !state.clipRole.includes("aicz"),
                  meta: {
                    title: "AI创作",
                  },
                },
                {
                  name: "spzncf",
                  disabled: !state.clipRole.includes("spzncf"),
                  meta: {
                    title: "视频智能拆分",
                  },
                },
                {
                  name: "tqspwz",
                  disabled: !state.clipRole.includes("tqspwz"),
                  meta: {
                    title: "提取视频文案",
                  },
                },
                {
                  name: "sptq",
                  disabled: false,
                  meta: {
                    title: "视频提取",
                  },
                },
                {
                  name: "sptqyp",
                  disabled: false,
                  meta: {
                    title: "视频提取音频",
                  },
                },
                {
                  name: "spqcyp",
                  disabled: false,
                  meta: {
                    title: "视频去除音频",
                  },
                },
                {
                  name: "sqcj",
                  disabled: false,
                  meta: {
                    title: "视频裁剪",
                  },
                },
                {
                  name: "sqzmcc",
                  disabled: false,
                  meta: {
                    title: "视频擦除字幕",
                  },
                },
                {
                  name: "sqccbz",
                  disabled: false,
                  meta: {
                    title: "视频擦除标志",
                  },
                },
                {
                  name: "spfy",
                  disabled: false,
                  meta: {
                    title: "视频翻译",
                  },
                },
                {
                  name: "spsczm",
                  disabled: false,
                  meta: {
                    title: "视频生成字幕",
                  },
                },
              ];
            }
          });
        } else if (item.name === "MaterialCenter") {
          item.children?.forEach((v1) => {
            if (v1.name === "TemplateList") {
              // v1.disabled = !state.clipRole.includes("twjj")
              v1.children = [
                {
                  name: "mbgc",
                  disabled: !state.clipRole.includes("mbgc"),
                  meta: {
                    title: "模版广场",
                  },
                },
                {
                  name: "myTemplate",
                  disabled: !state.clipRole.includes("myTemplate"),
                  meta: {
                    title: "我的模板",
                  },
                },
              ];
            }
          });
        }
      });

      const formatTree = (data) => {
        return data.map((item) => {
          return {
            disabled: item.disabled,
            key: item.name,
            title: item.meta.title,
            children:
              item.children && item.children.length
                ? formatTree(item.children)
                : [],
          };
        });
      };
      // 格式化路由tree
      let shotStackRoutes = formatTree(filterHideRoutes);

      state.treeData = shotStackRoutes;

      state.treeData = state.treeData.map((item) => {
        if (item.title === "视频发布" && item.children.length > 0) {
          item.children = item.children.filter((v1) => v1.title !== "账号中心");
        }
        return item;
      });

      function moveCommentMessageToTop() {
        for (let i = 0; i < state.treeData.length; i++) {
          if (
            state.treeData[i].key === "MatrixMarketing" &&
            Array.isArray(state.treeData[i].children)
          ) {
            for (let j = 0; j < state.treeData[i].children.length; j++) {
              if (state.treeData[i].children[j].key === "CommentMessage") {
                const commentMessageNode = state.treeData[i].children.splice(j, 1)[0];

                if (state.treeData.length > 1) {
                  state.treeData.splice(state.treeData.length - 1, 0, commentMessageNode);
                } else {
                  state.treeData.push(commentMessageNode);
                }

                return;
              }
            }
          }
        }
		}

      moveCommentMessageToTop();
    };

    getTreeData();

    const modelRef = reactive({
      name: "",
      status: false,
      selectedKeys: [],
      expandedKeys: [],
      checkedKeys: [],
    });
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: "请输入用户名",
        },
      ],
      checkedKeys: [
        {
          required: true,
          message: "请选择权限",
        },
      ],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const cancelClick = () => {
      resetFields();
      emit("onCancel");
    };

    const confirmClick = () => {
      validate().then(() => {
        addRole();
        resetFields();
      });
    };

    const title = computed(() => {
      return props.id ? "编辑角色" : "添加角色";
    });

    const getDetail = () => {
      state.loading = true;
      request
        .get("/work_ai", "/user/team/role/get", {
          id: props.id,
        })
        .then((res) => {
          modelRef.name = res.result.name;
          modelRef.status = res.result.status == 1 ? true : false;
          let checkedList = res.result.data;
          let keyArr = [
            "znjj",
            "yjcp",
            "ksjj",
            "jbjj",
            "twjj",
            "wzzyy",
            "aicz",
            "spzncf",
            "tqspwz",
          ];

          keyArr.forEach((item) => {
            if (checkedList.includes(item) && !state.clipRole.includes(item)) {
              checkedList = checkedList.filter((i) => i !== item);
            }
          });

          modelRef.checkedKeys = checkedList;

          function getAllChildKeys(node, treeData) {
            let keys = [];
            if (node.children && node.children.length > 0) {
              node.children.forEach((child) => {
                keys.push(child.key);
                keys = keys.concat(getAllChildKeys(child, treeData));
              });
            }
            return keys;
          }

          function updateCheckedKeysWithChildren() {
            const checkedKeysSet = new Set(modelRef.checkedKeys);

            modelRef.checkedKeys.forEach((key) => {
              const node = state.treeData.find((n) => n.key === key);

              if (node) {
                const childKeys = getAllChildKeys(node, state.treeData);

                childKeys.forEach((childKey) => checkedKeysSet.add(childKey));
              }
            });
            modelRef.checkedKeys = Array.from(checkedKeysSet);
          }

          updateCheckedKeysWithChildren();

          state.loading = false;
        });
    };

    const getPackageRole = () => {
      request
        .get("/work_ai", "/user/team/role/package")
        .then((res) => {
          state.clipRole = res.result;
          getTreeData();
        })
        .catch(() => {
          getTreeData();
        });
    };

    const addRole = () => {
      let url = "/user/team/role/add";
      let method = "post";

      let params = {
        status: modelRef.status ? 1 : 0,
        data: modelRef.checkedKeys,
        name: modelRef.name,
      };

      if (props.id) {
        params.id = props.id;
        url = "/user/team/role/update";
        method = "put";
      }
      request[method]("/work_ai", url, params).then((res) => {
        message.success("操作成功");
        emit("onConfirmRole");
      });
    };

    const onNodeClick = (selectedKeys, e) => {
      const keyToModify = selectedKeys[0];

      // 检查该键是否已经在数组中
      const index = modelRef.checkedKeys.indexOf(keyToModify);

      // 如果存在，则删除
      if (index > -1) {
        modelRef.checkedKeys.splice(index, 1);
      }
      // 如果不存在，则添加
      else {
        modelRef.checkedKeys.push(keyToModify);
      }
    };

    watch(
      () => props.visible,
      (visible) => {
        if (visible) {
          getPackageRole();
        }
        if (visible && props.id) {
          getDetail();
        }
      }
    );
    return {
      ...toRefs(state),
      title,
      onNodeClick,
      cancelClick,
      confirmClick,
      validateInfos,
      resetFields,
      modelRef,
    };
  },
});
</script>

<style lang="less" scoped>
.loading-wrapper {
  height: 60vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
